/*
 * (c) 2013 
 * 
 * Project       : Presensi
 * Filename      : JSONHelper.java
 * Creation Date : Apr 8, 2013 time : 9:55:14 AM
 *
 */

package id.khairizalnetani.tugasakhir;

import id.khairizalnetani.tugasakhir.entity.ErrorCheck;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONHelper
{
	private InputStream		is					= null;
	private JSONObject		jsonObject			= null;
	private String			json				= "";

	private final String	TAG_ID				= "id";
	private final String	TAG_ERROR			= "error";
	private final String	TAG_MESSAGE_ERROR	= "error_message";

	// method utama json helper untuk request ke web
	public JSONObject getJSONFromURL(String url)
	{
		try
		{
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (ClientProtocolException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);

			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}

			is.close();
			json = sb.toString();
		} catch (Exception e)
		{
			// TODO: handle exception
		}

		try
		{
			jsonObject = new JSONObject(json);

		} catch (JSONException e)
		{
			// TODO: handle exception
		}

		return jsonObject;
	}

	// untuk cek error
	public ErrorCheck cekUpload(JSONObject jsonObject)
	{
		ErrorCheck check = new ErrorCheck();
		try
		{
			check.setIdReport(jsonObject.getInt(TAG_ID));
			check.setKodeError(jsonObject.getInt(TAG_ERROR));
			check.setMessageError(jsonObject.getString(TAG_MESSAGE_ERROR));

		} catch (JSONException e)
		{
			Utils.TRACE("Error : upload laporan " + e.getMessage());
		}

		return check;

	}
}
